package com.example.kafkalearn.interceptor;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Map;

/**
 * @author He Changjie on 2021/6/24
 */
public class ProducerInterceptor implements org.apache.kafka.clients.producer.ProducerInterceptor<String, String> {
    private volatile long sendSuccess = 0;
    private volatile long sendFailure = 0;
    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord) {
        String value = "perfix-" + producerRecord.value();
        return new ProducerRecord<>(producerRecord.topic(), producerRecord.partition(), producerRecord.timestamp(), producerRecord.key(), value, producerRecord.headers());
    }

    @Override
    public void onAcknowledgement(RecordMetadata recordMetadata, Exception e) {
        if(e == null){
            sendSuccess++;
        } else {
            sendFailure++;
        }
    }

    @Override
    public void close() {
        double v = (double) sendSuccess / (sendFailure + sendSuccess);
        System.out.println("发送成功率："+String.format("%.1f", v * 100)+"%");
    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
